package softtech.apps.callblocker;

import com.tag.trivialdrivesample.util.IabHelper;
import com.tag.trivialdrivesample.util.IabResult;
import com.tag.trivialdrivesample.util.Inventory;
import com.tag.trivialdrivesample.util.Purchase;

import softtech.apps.utility.ApplicationConstants;
import softtech.apps.utility.FileUtility;import android.annotation.SuppressLint;import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

public class ActivityActiveApplication extends Activity {

	// Debug tag, for logging
	static final String TAG = "Activity Active Application";

	// In App Billing
	IabHelper mHelper;
	// ITEM
	static final String ITEM_SKU = "receive_voice_massage"; // dat ten la con me
															// gi cung duoc

	static final String ITEM_SKU2 = "do_chet_tiet";

	SharedPreferences preferences;
	Boolean isPurchased = false; // bien luu giu tinh trang da purchase hay chua
	static final int RC_REQUEST = 10001;

	Context mContext;

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_activate_application);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		mContext = this;

		String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgWR7HMdeZSan5Nu1G9WEDYPq/+M5bhjQjyhxo6IUztQkS/sGBthH8tTTRXpJfYqxwyHYII+BzEPeiLyYydXpXg/6zsEGRDC8jvhi0fNGMz28f9v0NcksK/EJkmXEwL2harqNvAiddih5OzaKGc3YW2tBDcXlt8qz6jd0EjiTwAplCzsZrCfbJAIiU/YQoSPGlfx2seobw5e44B5e2ZK/wsuUpd1+jH+gXfKkn9NhBgsdMFmhjRf248wV9Qse/qARPTFIEvkvaEDmyBntY1DlWMuhsVNrnDjoRP6LrkwJGGRmqX5sXGZNlQP84ZesykqCsvkdfyQiUEYOJTWUxxrPBwIDAQAB";

		mHelper = new IabHelper(this, base64EncodedPublicKey);
		mHelper.enableDebugLogging(true);
		mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {

			@Override
			public void onIabSetupFinished(IabResult result) {
				
				if (!result.isSuccess()) {
					complain("Problem setting up in-app billing: " + result);
					return;
				}
				if (mHelper == null)
					return;
				if (isPurchased == true) {
					// complain("This product has purchased");
				} else {
					complain("This product hasn't purchased yet, buy full version to use full feature");
				}
			}
		});

		if (isPurchased) {
			// ENDable chuc nang gi do
		} else {
			// disable chuc nang gi do
		}

		// ////////////////////////////////////////////////////////////////////
		// Khai bao 1 button lam nhiem vu buy
		findViewById(R.id.btBuyFullVersion).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				buyClick(v);
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + ","
				+ data);

		// Pass on the activity result to the helper for handling
		if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
			// not handled, so handle it ourselves (here's where you'd
			// perform any handling of activity results not related to in-app
			// billing...
			super.onActivityResult(requestCode, resultCode, data);
		} else {
			Log.d(TAG, "onActivityResult handled by IABUtil.");
		}
	}

	// We're being destroyed. It's important to dispose of the helper here!
	@Override
	public void onDestroy() {
		// very important:
		try {
			Log.d(TAG, "Destroying helper.");
			if (mHelper != null)
				mHelper.dispose();
			mHelper = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	void saveData() {

		/*
		 * WARNING: on a real application, we recommend you save data in a
		 * secure way to prevent tampering. For simplicity in this sample, we
		 * simply store the data using a SharedPreferences.
		 */

		SharedPreferences.Editor spe = getPreferences(MODE_PRIVATE).edit();
		spe.putBoolean("isPurchased", true);
		spe.commit();
		
		saveFileLicense(1);
		// Log.d(TAG, "Saved data: tank = " + String.valueOf(isPurchased));
	}

	void loadData() {
		SharedPreferences sp = getPreferences(MODE_PRIVATE);
		isPurchased = sp.getBoolean("isPurchased", false);
		// Log.d(TAG, "Loaded data: Purchase = " + String.valueOf(isPurchased));
	}

	void complain(String message) {
		// Log.e(TAG, "**** TrivialDrive Error: " + message);
		alert("Error: " + message);
	}

	void alertMessage(String message) {
		AlertDialog.Builder bld = new AlertDialog.Builder(this);
		bld.setMessage(message);
		bld.setNeutralButton("OK", null);
		// Log.d(TAG, "Showing alert dialog: " + message);
		bld.create().show();
	}

	public boolean hasConnections() {
		ConnectivityManager cm = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (null == ni)
			return false;
		return ni.isConnectedOrConnecting();
	}

	public void buyClick(View v) {
		if (isPurchased == true) {
			complain("You app is purchased!");
			return;
		}

		String payload = "aaaaE$^%&%^&%&JKJKHJKHJK";

		mHelper.launchPurchaseFlow(this, ITEM_SKU, RC_REQUEST,
				mPurchaseFinishedListener, payload);

	}

	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {

		@Override
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

			if (mHelper == null)
				return;
			if (result.isFailure()) {
				if (result.getResponse() == 7) {
					isPurchased = true;
					saveData();
				} else {
					// complain("Loi khi purchase: " + result);
					complain("Something wrong, Connect to the internet as please try agian !!");
				}
				return;
			}
			if (!verifyDeveloperPayload(purchase)) {
				complain("Error purchasing. Authenticity verification failed.");
				return;
			}
			// Log.d(TAG, "Purchase successful.");

			if (purchase.getSku().equals(ITEM_SKU)) {
				// Log.d(TAG, "Purchase is gas. Starting gas consumption.");
				mHelper.consumeAsync(purchase, mConsumeFinishedListener);
			} else if (purchase.getSku().equals(ITEM_SKU2)) {
				// Log.d(TAG, "Purchase is gas. Starting gas consumption.");
				mHelper.consumeAsync(purchase, mConsumeFinishedListener);
			}
		}
	};

	IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
		public void onQueryInventoryFinished(IabResult result,
				Inventory inventory) {
			if (mHelper == null)
				return;
			if (result.isFailure()) {
				// Handle failure
				// Log.d(TAG, "Click buy button to reactive app");
				if (result.getResponse() == 7) {
					isPurchased = true;
					saveData();
				} else {
					// complain("Loi khi purchase: " + result);
					complain("Something wrong, Connect to the internet as please try agian !!");
				}
				// return;
			}

			// Log.d(TAG, "Query inventory was successful.");

			// Check for gas delivery -- if we own gas, we should fill up the
			// tank immediately
			Purchase gasPurchase = inventory.getPurchase(ITEM_SKU);
			Purchase gasPurchase2 = inventory.getPurchase(ITEM_SKU2);
			if (gasPurchase != null && verifyDeveloperPayload(gasPurchase)) {
				// Log.d(TAG, "We have gas. Consuming it.");
				mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
						mConsumeFinishedListener);
				return;
			} else if (gasPurchase2 != null
					&& verifyDeveloperPayload(gasPurchase2)) {
				// Log.d(TAG, "We have gas. Consuming it.");
				mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU2),
						mConsumeFinishedListener);
				return;
			}
			// Log.d(TAG,
			// "Initial inventory query finished; enabling main UI.");

		}
	};
	IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {

		@Override
		public void onConsumeFinished(Purchase purchase, IabResult result) {

			// if we were disposed of in the meantime, quit.
			if (mHelper == null)
				return;
			if (result.isSuccess()) {
				// Log.d(TAG, "Consumption successful. Provisioning.");
				isPurchased = true;
				saveData();
				alert("You are purchased, please restart app to apply");
				// btEnableReceiveVoiceMessage.setEnabled(true);
				// tvReceiveVoiceMessageTitle.setTextColor(Color
				// .parseColor("#ffffff"));
				// textView3.setTextColor(Color.parseColor("#ffffff"));
				// btBuyFullVersion.setEnabled(false);
			} else {
				complain("Error while consuming: " + result);
			}
			// Log.d(TAG, "End consumption flow.");
		}
	};

	boolean verifyDeveloperPayload(Purchase p) {
		String payload = p.getDeveloperPayload();

		return true;
	}

	void alert(String message) {
		AlertDialog.Builder bld = new AlertDialog.Builder(this);
		bld.setMessage(message);
		bld.setNeutralButton("OK", null);
		Log.d(TAG, "Showing alert dialog: " + message);
		bld.create().show();
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	
	@Override
	public void onBackPressed() {
		Intent in = new Intent( mContext , ActivityDashboard.class );
		startActivity(in);
		finish();
	}

	/**
	 * Save file license
	 */
	public void saveFileLicense(int license){
		FileUtility futil = new FileUtility();
		//
		// create folder
		//
		FileUtility.createDirIfNotExists(ApplicationConstants.PATH_FOLDER_LICENSE);
		
		//
		// check old file
		//
		String old_file_sdcard = futil.getContentFileFromSdcard(ApplicationConstants.PATH_FOLDER_LICENSE, ApplicationConstants.FILE_ACTIVATE_NAME);
		String old_file_in_app = futil.LoadContentFile(mContext, ApplicationConstants.FILE_ACTIVATE_NAME);
		
		if(FileUtility.checkStringNotNull(old_file_sdcard) && FileUtility.checkStringNotNull(old_file_in_app)){
			return;
		}

		//
		// create file if not exist
		//
		if(!FileUtility.checkStringNotNull(old_file_sdcard)){
			futil.saveContentFileToSdCard(String.valueOf(license), ApplicationConstants.PATH_FOLDER_LICENSE, ApplicationConstants.FILE_ACTIVATE_NAME);
		}
		
		if(!FileUtility.checkStringNotNull(old_file_in_app)){
			futil.SaveContentFile(mContext , ApplicationConstants.FILE_ACTIVATE_NAME, String.valueOf(license));
		}
	}
	
}
